<template>
    <div class="allbox">
            <!-- 功能选择区 -->
            <div class="selection">
            <div @click="refresh(1)">
                <el-button type="info"><el-icon><RefreshRight /></el-icon></el-button>
            </div>
            <div @click="add()">
                <el-button type="success"><el-icon size="22" style="margin-right: 2px;"><Plus /></el-icon>添加</el-button>
            </div>
        </div>
        <!-- table -->
        <div class="table_box">
            <el-table  :data="tableData" height="90vh" @row-dblclick="db_Click"> <!--单击 和 双击 && 单选 和全选 -->
                <el-table-column type="selection" width="100" align="left" />
                    <!-- <el-table-column label="序号" width="80" type="index"/> -->
                    <el-table-column label="序号" width="80">
                        <template #default="scope">
                        <div :slot-scope="scope.$index">
                            {{ (scope.$index+1) + ((currentIndex-1)*currentSize) }}
                        </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="name" label="品名" width="200"/>
                    <el-table-column label="品牌名称" width="150" type="index" align="center">
                        <template #default="scope">
                            <div :slot-scope="scope.$index">
                            {{ tableData[scope.$index].brand.name }}
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="price" label="价格" width="80" align="center"/>
                    <el-table-column prop="fake_price" label="指导价格" width="80" align="center" />
                    <el-table-column label="封面图片" width="150" type="index" align="center">
                    <template #default="scope">
                        <div style="display: flex; justify-content: center;" :slot-scope="scope.$index">
                            <el-image :src="tableData[scope.$index].startImage" style="height: 140px;border-radius: 10px;"/> 
                        </div>
                    </template>
                    </el-table-column>
                    <el-table-column prop="desc" align="center" class-name="el_tale_column_class" label="产品描述" width="350" hidden style="height: 200px;" />
                    
                    <el-table-column fixed="right" label="执行操作" width="150" align="center">
                    <template #default="scope">
                    <div>
                            <el-button type="danger" style="width: 140px;"  @click.prevent="del(scope.$index)">
                                <el-icon size="20"><DeleteFilled /></el-icon>删除
                            </el-button>
                    </div>
                    </template>
                </el-table-column>
            </el-table>
        <el-pagination
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            :page-sizes="pageSize"
            :page-size="pageSize[0]"
            v-model:current-page="currentIndex"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
            class="mt-4"
        />
        </div>
          <!-- form表单 -->
        <el-dialog
            v-model="dialogVisible"
            title="编辑表单"
            draggable
            width="35%">
            <el-form :model="form" class="demo-ruleForm" size="large">

            <el-form-item required label="品名" label-width="120px">
                <el-input v-model="form.name" type="text" autocomplete="off" placeholder="请输入品名" />
            </el-form-item>

            <el-form-item required label="产品描述" label-width="120px">
                <el-input v-model="form.desc" type="text" autocomplete="off" placeholder="请输入产品的详细描述" />
            </el-form-item>
            
                <!-- 判断是否为修改还是新增 -->
            <el-form-item required label="产品图片" label-width="120px" class="edit_line">
                <el-upload
                    v-model:fileList="fileList"
                    action="http://127.0.0.1:9000/upload"
                    list-type="picture-card"
                    :drag="true"
                    :on-remove="handleRemove"
                    :on-change="onUpload" 
                    :on-success="uploadSuccess"
                    ref="ref_upload">
                    <el-icon style="margin-top: 10px;color:darkturquoise;" size="40"><UploadFilled /></el-icon>
                </el-upload>
            </el-form-item>

            <el-form-item required label="现价" label-width="120px">
                <el-input v-model="form.price" type="text" autocomplete="off" placeholder="请输入优惠后的价格" />
            </el-form-item>

            <el-form-item required label="原价" label-width="120px">
                <el-input v-model="form.fake_price" type="text" autocomplete="off" placeholder="请输入打折价格" />
            </el-form-item>

            <el-form-item required label="地区" label-width="120px">
              <el-select v-model="form.from" placeholder="请选择车辆出产地" style="width:80%;">
                <div  v-for="(item,index) in china_city" :key="index">
                  <el-option :label="item" :value="item"></el-option>
                </div>
              </el-select>
            </el-form-item>

            <el-form-item required label="品牌" label-width="120px">
              <el-select v-model="form.brandId" placeholder="请选择汽车品牌" style="width:80%;">
                <el-option
                    v-for="item in brandList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                    >
                    <span style="float: left">{{ item.name }}</span>
                    <span
                        style="
                        float: right;
                        color: var(--el-text-color-secondary);
                        font-size: 13px;
                        "
                        >{{ item.id }}</span
                    >
                    </el-option>
              </el-select>
              
            </el-form-item>
            

            </el-form>
        <template #footer>
            <span class="dialog-footer">
            <el-button type="primary" @click="submit()" style="width: 80%;margin-right: 8%;height: 40px;">
                {{ btn_text }}
            </el-button>
            </span>
        </template>
        </el-dialog>

        <messageComp ref="ref_messageComp"> </messageComp>
    </div>
  
</template>

<script setup>
import axios from "axios"
import { ref,getCurrentInstance,watch } from "vue"
import { useStore } from "vuex";
import messageComp from "../components/messageComp.vue";
const ref_messageComp = ref(null) //弹窗message组件refs
const store = useStore()

// 数据
let china_city = ref(["北京", "上海", "天津", "重庆", "河北", "山西", "内蒙古", "辽宁", "吉林", "黑龙江", "江苏",
"浙江", "安徽", "福建", "江西", "山东", "河南", "湖北", "湖南", "广东", "广西", "海南", "四川",
"贵州", "云南", "西藏", "陕西", "甘肃", "宁夏", "青海", "新疆", "香港", "澳门",
"台湾", "Foreign"],)
let dialogVisible = ref(false) //表单开关
let form = ref({}) //表单数据 el-form
let fileList = ref([]) //上传的图片
let tableData = ref([]) //表格数据-el-table
let orginList = ref([]) //原始数据
let pageSize = ref([5, 10, 50, 99999])
let beforeIndex = ref(1)//之前的索引
let currentIndex = ref(1) //当前的索引
let currentSize = ref(pageSize.value[0]) //当前可视数量
let brandList = ref([]) //品牌列表
let total = ref(0) //总数
let btn_text = ref('添加')
// 提交
const submit = ()=>{
    if (btn_text.value == '添加') {
        addAPI()
    } else {
        updateAPI()
    }
   
}

const handleSizeChange = (e)=>{
    console.log(e);
    currentSize.value = e
    tableData.value = []
    ref_messageComp.value.loading({dom:'.table_box',text:'Loading..',},500,()=>{
        return handleCurrentChange(currentIndex.value,e);
    })
}
const handleCurrentChange = (e,_pageSize)=>{
    _pageSize = currentSize.value
    console.log(e,_pageSize);
    tableData.value = orginList.value.slice((_pageSize*e) -_pageSize,_pageSize*e)
    beforeIndex.value = e

}

const db_Click = (e)=>{
    fileList.value = [{
        url:e.startImage
    }]
    dialogVisible.value = true
    btn_text.value = '修改'
    form.value = e
}

const updateAPI = () =>{
    dialogVisible.value = false
    axios({
        method:'post',
        url:store.state.url + '/cars/update',
        data:form.value,
    }).then(res=>{
        // console.log(res)
        if (res.data.code == 200) {
            ref_messageComp.value.messageSuccess('恭喜您，修改了一条记录')
            refresh()
            form.value = {}//清掉原数据
        }else{
            ref_messageComp.value.messageFail(`修改失败,${res.data.message}`)
        }
    }).catch(err=>{
        console.log(err)
        ref_messageComp.value.messageNetFail('网络连接失败，请检查服务器')
    })
}
const addAPI = ()=>{
    dialogVisible.value = false
    axios({
        method:'post',
        url:store.state.url + '/cars/insert',
        data:form.value,
    }).then(res=>{
        console.log(res.data);
        if (res.data.code == 200) {
            ref_messageComp.value.messageSuccess('恭喜您，新增了一条记录')
            refresh()
            form.value = {}//清掉原数据
        }else{
            ref_messageComp.value.messageFail(`新增失败,${res.data.message}`)
        }
    }).catch(err=>{
        ref_messageComp.value.messageNetFail('网络连接失败，请检查服务器')
    })
}

const getData = ()=>{
    axios({
        url:store.state.url + '/cars'
    }).then(res=>{
        console.log(res);
        if (res.data.code == 200) {
            let arr = res.data.data
            total.value = arr.length
            orginList.value = arr
            tableData.value = arr.slice(0,currentSize.value)
            // tableData.value = arr
            getBrandData()
        }
    }).catch(err=>{
        ref_messageComp.value.messageNetFail('网络连接失败，请检查服务器')
    })
}
// 获取所有品牌信息
const getBrandData = ()=>{
    axios({
        url:store.state.url + '/brands'
    }).then(res=>{
        console.log(res);
        if (res.data.code == 200) {
            let arr = res.data.data
            brandList.value = arr
        }
    }).catch(err=>{
        ref_messageComp.value.messageNetFail('网络连接失败，请检查服务器')
    })
}


// 删除
const del = (index)=>{

    let timer = setInterval(() => {
        axios({
            method:'post',
            url:store.state.url + '/cars/delete',
            data:{
                id:tableData.value[index].id
            },
        }).then(res=>{
            if (res.data.code == 200) {
                ref_messageComp.value.messageSuccess('您删除了一条记录')
                refresh()
            }else{
                ref_messageComp.value.messageFail('删除失败！')
            }
        }).catch(err=>{
            ref_messageComp.value.messageNetFail('网络连接失败，请检查服务器')
        })

        clearInterval(timer)
    }, 1000);

}
// 刷新
const refresh = (n)=>{
    tableData.value = []
    if (n) {
        ref_messageComp.value.loading({dom:'.allbox',text:'数据拉取中..',},1000,()=>{
            ref_messageComp.value.messageSuccess('刷新成功')
            getData()
        })
        return;
    }
    getData()
}
const add = ()=>{
    form.value = {}
    dialogVisible.value = true
    btn_text.value = '添加'

}
// 上传成功
const uploadSuccess = (data)=>{
    // console.log(data);
    form.value.startImage = data.data.url
}
const handleRemove = (e,val)=>{ //删除编辑面板-上传图片
    console.log('删除图片',e);
    console.log('还剩余图片',val); 
    // 记住这个数组  这个是人家自带的
}
const onUpload = (e,val)=>{ //删除编辑面板-上传图片
    fileList.value = [] //清空数组否则累加图片了
    fileList.value.push(e)
    console.log('每上传一张图片',fileList.value);
}
// 执行区
refresh()
</script>


<style scoped>
.role{
    position: absolute;
    top: 0%;
    left: 0px;
    width: 100%;
    height: 100%;
    border: 2px solid #ccc;
    color: black;
    border-radius: 10px;
    /* border: 1px solid ; */
}
.selection{
    margin: 10px;
    width: 100%;
    height: 40px;
    line-height: 40px;
    /* border: 2px solid; */
    display: flex;

}
.selection>div{
    width: 70px;
    height: 100%;
    margin-left: 10px;
    border-radius: 5px;
}
/* 刷新 */
.selection>div:nth-child(1){
    margin-left: 40px;
}
.roles{
    width: 40%;
    margin: 5px;
    /* border: 2px solid ; */
}
.datetime{
    width: 100%;
    height: 40px;
    text-align: left;
    letter-spacing: 1px;
    color: gray;
    /* border: 2px solid #ccc; */
}


</style>